#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: owefsad@huoxian.cn
# project: dongtai-webapi

import csv
import logging

from django.contrib.auth.models import Group
from dongtai_common.models import User
from dongtai_common.models.department import Department

from dongtai_common.endpoint import R
from dongtai_common.endpoint import SystemAdminEndPoint
from dongtai_web.notify.email import Email
from dongtai_conf import settings
from django.utils.translation import gettext_lazy as _
import string
import random
logger = logging.getLogger("dongtai-webapi")

GONG_ZHONG_HAO_IMAGE = ""

class UserRegisterEndPoint(SystemAdminEndPoint):
    authentication_classes = ()
    permission_classes = ()

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        try:
            self.email = Email()
            self.email.login_server(server=settings.EMAIL_SERVER,
                                    username=settings.EMAIL_USER,
                                    port=settings.EMAIL_PORT,
                                    pwd=settings.EMAIL_PASSWORD,
                                    ssl=settings.ENABLE_SSL)
        except Exception as e:
            self.email = None
            pass

    def get(self, request):
        users = self.read_user_data()
        self.register(users)
        return R.success(msg=_('Account has been created successfully'))

    def post(self, request, token):
        """
        {
            "form": "xJfeTv",
            "entry": {
                "field1": 123,
                "field2": "Hello, World",
                "field3": "It's very good."
            }
        }
        :param request:
        :param token:
        :return:
        """

        webhook_token = settings.config.get('wenjuan_webhook', 'token')
        if token == webhook_token:
            entry = request.data['entry']
            username = entry['field_1']
            phone = entry['field_2']
            email_addr = entry['field_3']

            _user = User.objects.filter(username=username).first()
            if _user:
                logger.info(_('User {} already exists').format(username))
            else:
                self.register_with_raw(username=username, phone=phone, email_addr=email_addr, email=self.email)
                logger.info(_('User {} has been created successfully').format(username))
        else:
            logger.warn(_('Failed to create user, error message: token is incorrect'))
        return R.success(msg=_('Account registration successful'))

    def read_user_data(self):
        header = True
        users = list()
        try:

            with open('/tmp/user_register.csv', newline='', encoding='utf-8') as f:
                reader = csv.reader(f)
                for row in reader:
                    if header:
                        header = False
                        continue
                    users.append((row[11].strip(), row[12].strip(), row[13].strip()))
        except:
            print(_('User account file read error'))
        return users

    @staticmethod
    def register_with_raw(username, email_addr, phone, email):
        random_str = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(3))
        password = f'{username}@{random_str}'
        new_user = User.objects.create_user(username=username, password=password, email=email_addr, phone=phone)
        department = Department.objects.filter(id=1).first()
        department.users.add(new_user)
        group, success = Group.objects.get_or_create(name='user')
        group.user_set.add(new_user)
        res= email.sendmail(
            from_addr=settings.EMAIL_FROM_ADDR,
            to_addrs=[email_addr, settings.ADMIN_EMAIL],
            _subject='【洞态IAST】账号创建成功',
            _content=f'''<h3>洞态IAST账号创建成功</h3><span>登陆地址：</span>https://iast.io/login<br></br>账号：{username}<br></br>密码：{password}<br></br><br/>登陆之后，请马上修改默认密码，然后重新登陆使用。<br/><br></br>官方网站：https://dongtai.io<br/><br></br><br>官方公众号：洞态公众号二维码</br><img width="400px" height="400px" src="{GONG_ZHONG_HAO_IMAGE}" ><hr></hr><h3>Welcome to DongTai IAST,
    your account has been succefully created.</h3><span>Login URL:</span>https://iast.io/login<br></br>Account：{username}<br></br>Password：{password}<br></br><br/>Notice: You MUST change the password during the first time log in. Password can be changed at "Settings/Account".  After that, you can log in again.<br/>DongTai IAST Official Website: https://dongtai.io<br/><br></br><br>DongTai IAST WeChat Official Account: DongTai IAST's QR Code </br><img width="400px" height="400px" src="{GONG_ZHONG_HAO_IMAGE}">''',
            content_type='html',
        )
        print(res)

    def register(self, users):
        if users:
            email = Email()
            email.login_server(server=settings.EMAIL_SERVER,
                               username=settings.EMAIL_USER,
                               pwd=settings.EMAIL_PASSWORD,
                               ssl=settings.ENABLE_SSL)
            for user in users:
                _user = User.objects.filter(username=user[0]).first()
                if _user:
                    print(f'用户{user[0]}已存在')
                else:
                    self.register_with_raw(username=user[0], email_addr=user[1], phone=user[2], email=self.email)
            self.email.logout_server()
